<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="供应商" prop="name">
        <el-select
          v-model="queryParams.name"
          remote
          clearable
          filterable
          :filter-method="hospitalFilter"
          placeholder="请选择供供应商"
          class="!w-240px"
        >
          <el-option
            v-for="item in supplierList"
            :key="item.name"
            :label="item.name"
            :value="item.name"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表-->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" row-key="id" :stripe="true" :show-overflow-tooltip="true" @selection-change="handleSelectionChange" ref="tableRef">
      <el-table-column width="30" label="选择" type="selection" />
      <el-table-column label="供应商编号" align="center" prop="id" />
      <el-table-column label="名称" align="center" prop="name" />
      <el-table-column prop="minOrderQuantity" label="最小起订量" width="180">
        <template v-slot="scope">
          <el-input v-model="scope.row.minOrderQuantity" placeholder="请输入最小起订量" />
        </template>
      </el-table-column>

      <el-table-column label="默认供应商" width="180"> 
        <template v-slot="scope" >
          <el-checkbox :disabled="isRowAlreadyDefault(scope.row)" v-model="scope.row.isDefault" @change="handleDefaultChange(scope.row)" >
            {{scope.row.isDefault == true ?"是":"否"}}
          </el-checkbox>
        </template>
      </el-table-column>
    </el-table>
    <!--分页--> 
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap> 
</template>
<script setup lang="ts">
import debounce from 'lodash/debounce'
import { dateFormatter } from '@/utils/formatTime'
import { ProductCategoryApi, ProductCategoryVO } from '@/api/spd/product/category'
import { ProductUnitApi, ProductUnitVO } from '@/api/spd/product/unit'
import { SupplierApi, SupplierVO } from '@/api/spd/purchase/supplier'
import { RelationshipApi, RelationshipVO } from '@/api/spd/relationship'
import { defaultProps, handleTree } from '@/utils/tree'
import { ref, reactive, watch, nextTick } from 'vue'

const props = defineProps<{
  id: number // 产品编号（主表的关联字段）
}>()
const total = ref(0) // 列表的总页数
const loading = ref(true) // 列表的加载中
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  name: undefined,
  id: undefined,
  supplierId: undefined,
  productId: 0,
})
const queryFormRef = ref() // 搜索的表单
const supplierList = ref<SupplierVO[]>([]) // 供应商列表
const list = ref<SupplierVO[]>([]) // 列表的数据
const tableRef = ref<InstanceType<typeof ElTable>>() // 表格引用
const formRef = ref() // 表单 Ref
const selectionList = ref<SupplierVO[]>([]) // 保存所有勾选的数据
const productIds = ref<RelationshipVO[]>([])

watch(() => props.id, async (newId) => {
  if (newId !== undefined) {
    queryParams.productId = newId
    await getList()
  }
}, { immediate: true })

/** 查询列表 */
const getList = async () => {
  loading.value = true
  const prevSelectionList = [...selectionList.value] // 保存当前已勾选的数据
  try {
    queryParams.productId = props.id
    supplierList.value = await SupplierApi.getSupplierSimpleList()
    const data = await SupplierApi.getSupplierPage(queryParams)
    list.value = data.list
    total.value = data.total
    try {
      productIds.value = await RelationshipApi.getProductCategorySimpleBySupplie(queryParams.productId)
      
      if (tableRef.value && list.value.length > 0) {
        tableRef.value.clearSelection()
        list.value.forEach(item => {
          item.isDefault = false // 初始化为false，稍后再根据API返回的数据设置
        })
        await nextTick()
        if (productIds.value.length > 0) {
          productIds.value.forEach(productId => {
            const row = list.value.find(row => row.id === productId.supplierId)
            if (row) {
              row.isDefault = productId.sort === 1 // 设置isDefault状态
              if (row.isDefault) {
                tableRef.value?.toggleRowSelection(row, true) // 选中该行
              }
              tableRef.value?.toggleRowSelection(row, true)
            }
          })
        }
        // 恢复之前勾选的数据
        prevSelectionList.forEach(selectedItem => {
          const row = list.value.find(row => row.id === selectedItem.id)
          if (row) {
            tableRef.value?.toggleRowSelection(row, true)
          }
        })
      }
      return productIds.value
    } catch (error) {
      console.error('Failed to fetch pre-selected product IDs:', error)
      return [] // 在发生错误时返回一个空数组，或者您可以根据需求抛出错误
    }
  } finally {
    loading.value = false
  }
}

/** 查询列表 */
const selectList = async () => {
  const prevSelectionList = [...selectionList.value] // 保存当前已勾选的数据
  loading.value = true
  try {
    const data = await SupplierApi.getSupplierPage(queryParams)
    list.value = data.list
    total.value = data.total
    productIds.value = await RelationshipApi.getProductCategorySimpleBySupplie(queryParams.productId)
    list.value.forEach(item => {
      item.isDefault = false // 初始化为false，稍后再根据API返回的数据设置
    })
    await nextTick()
    productIds.value.forEach(productId => {
      const row = list.value.find(row => row.id === productId.supplierId)
      if (row) {
        row.isDefault = productId.sort === 1 // 设置isDefault状态
        if (row.isDefault) {
          tableRef.value?.toggleRowSelection(row, true) // 选中该行
        }
      }
    })
    // 恢复之前勾选的数据
    prevSelectionList.forEach(selectedItem => {
      const row = list.value.find(row => row.id === selectedItem.id)
      if (row) {
        tableRef.value?.toggleRowSelection(row, true)
      }
    })
  } finally {
    loading.value = false
  }
}

// 假设您有一个方法来检查某行是否已经是默认供应商
const isRowAlreadyDefault = (row) => {
  // 注意：这里需要确保 list.value 和 row.id 是正确定义的
  return list.value.some(r => r.isDefault === true && r.id !== row.id)
}

const handleDefaultChange = async (value) => {
  // 检查是否有其他行已经被设置为默认供应商
  const isOtherDefaultExists = list.value.some(r => r.isDefault === true && r.id !== value.id)
  if (isOtherDefaultExists) {
    console.log(value)
    alert("已存在默认供应商，请选择其他供应商作为默认。")
    return
  } 
  // 如果没有其他默认供应商，进行 API 调用并设置 sortId
  const productIds = await RelationshipApi.getProductCategorySimpleBySupplie(props.id)
  let sortId = productIds.length > 0 ? (value.isDefault ? "1" : "0") : ""
  console.log(sortId)
}

/** 搜索按钮操作 */
const handleQuery = async () => {
  queryParams.productId = props.id
  queryParams.pageNo = 1
  await selectList()
}

/** 重置按钮操作 */
const resetQuery = async () => {
  queryParams.id = undefined // 重置筛选条件
  queryParams.productId = props.id
  queryParams.pageNo = 1
  queryFormRef.value.resetFields()
  await selectList()
}

/**
 * 键入监听方法
 */
const hospitalFilter = (params) => {
  // 判断键入是否有值
  if (params !== "") {
    // 有值调用防抖方法
    debouncedSearch(params)
  } else {
    // 没有键入值，集合为空
    supplierList.value = []
  }
}

/**
 * 根据键入的值查询产品列表
 */
const productLists = async (params) => {
  // 加载产品列表
  const supplierData = await SupplierApi.getSupplierSimpleLists(params)
  supplierList.value = handleTree(supplierData, 'id')
}

// 创建一个防抖函数来处理搜索操作
const debouncedSearch = debounce((params) => {
  productLists(params)
}, 500) // 防抖等待时间为500毫秒  

/** 表单校验 */
const validate = () => {
  return formRef.value.validate()
}

/** 表单值 */
const getData = () => {
  return selectionList.value
}

/** 选中操作 */
const handleSelectionChange = (rows: SupplierVO[]) => {
  // 过滤掉之前已经存在的勾选数据，避免重复添加
  const newSelectedRows = rows.filter(row => !selectionList.value.some(selectedRow => selectedRow.id === row.id))
  selectionList.value = [...selectionList.value, ...newSelectedRows]
}

defineExpose({ validate, getData })
</script>